package com.wbase.permission.request

import android.os.Build
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager

/**
 * 权限检查器
 *
 * @author wangheng
 */
class PermissionRequester {

    companion object{
        private const val TAG = "PermissionRequester"
    }

    private var mFragment: PermissionRequestFragment

    constructor(activity: FragmentActivity){
        mFragment = getFragment(activity.supportFragmentManager)
    }

    constructor(fragment: Fragment){
        mFragment = getFragment(fragment.childFragmentManager)
    }

    private fun getFragment(fragmentManager: FragmentManager): PermissionRequestFragment {
        val fragment = fragmentManager.findFragmentByTag(TAG)
        if(fragment == null || fragment !is PermissionRequestFragment){
            if(fragment != null && fragment !is PermissionRequestFragment){
                fragmentManager.beginTransaction()
                    .remove(fragment)
                    .commitNow()
            }

            val newInstance = PermissionRequestFragment()
            fragmentManager.beginTransaction()
                .add(newInstance, TAG)
                .commitNow()
            return newInstance
        }else{
            return fragment
        }
    }

    fun requestPermissions(permissions: ArrayList<String>,
                           callback: (isAllGranted: Boolean,
                           isAllCantShow: Boolean,
                           deniedList: ArrayList<String>,
                           list: ArrayList<Permission>) -> Unit){
        if(!needCheckPermission()){
            val allGranted = true
            val allCantShow = false

            val resultList = ArrayList<Permission>()
            permissions.forEach {
                resultList.add(Permission(it, true, true))
            }

            callback(allGranted,allCantShow, ArrayList(),resultList)
            return
        }else{
            mFragment.requestPermissions(permissions,callback)
        }
    }

    private fun isPermissionGranted(permission: String): Boolean {
        return !needCheckPermission() && mFragment.isGranted(permission)
    }

    /**
     * 是否需要请求权限(只有大于或者等于SDK 23版本才需要请求权限)
     */
    private fun needCheckPermission(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    }
}